<template>
  <div class="app-container">
    <!-- Search Form -->
    <el-form
      ref="queryForm"
      :inline="true"
      :model="queryParams"
    >
      <el-form-item :label="$t('tool.openClient.appName')">
        <el-input
          v-model="queryParams.appName"
          :placeholder="$t('tool.openClient.appName')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('tool.openClient.appId')">
        <el-input
          v-model="queryParams.appId"
          :placeholder="$t('tool.openClient.appId')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleQuery"
        >
          {{ $t("tool.openClient.search") }}
        </el-button>
        <el-button @click="resetQuery">
          {{ $t("tool.openClient.reset") }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- Toolbar -->
    <el-row
      :gutter="10"
      class="mb-4"
    >
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['openclient:info:add']"
          type="primary"
          @click="handleAdd"
        >
          {{ $t("tool.openClient.add") }}
        </el-button>
      </el-col>
    </el-row>

    <!-- Table -->
    <el-table
      v-loading="loading"
      :data="list"
    >
      <el-table-column
        align="center"
        type="selection"
        width="55"
      />
      <el-table-column
        :label="$t('tool.openClient.appName')"
        prop="appName"
      />
      <el-table-column
        :label="$t('tool.openClient.appId')"
        prop="appId"
      />
      <el-table-column
        :label="$t('tool.openClient.appSecret')"
        prop="appSecret"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <div class="secret-display">
            <el-button
              :icon="secretVisibility.get(row.appId) ? 'ele-Hide' : 'ele-View'"
              link
              type="primary"
              @click="toggleSecret(row.appId)"
            ></el-button>
            <span>{{ secretVisibility.get(row.appId) ? row.appSecret : "****************" }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('tool.openClient.status')"
        prop="status"
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? $t(`tool.openClient.enabled`) : $t(`tool.openClient.disabled`) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('tool.openClient.createTime')"
        prop="createTime"
        width="180"
      />
      <el-table-column
        :label="$t('tool.openClient.operation')"
        align="center"
        width="150"
      >
        <template #default="{ row }">
          <el-button
            v-hasPermi="['openclient:info:update']"
            icon="ele-Edit"
            link
            type="primary"
            @click="handleUpdate(row)"
          ></el-button>
          <el-button
            v-hasPermi="['openclient:info:delete']"
            icon="ele-Delete"
            link
            type="danger"
            @click="handleDelete([row.id])"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <pagination
      v-show="total > 0"
      v-model:limit="queryParams.size"
      v-model:page="queryParams.current"
      :total="total"
      @pagination="handleQuery"
    />

    <!-- Dialog -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item
          :label="$t('tool.openClient.appName')"
          prop="appName"
        >
          <el-input v-model="form.appName" />
        </el-form-item>
        <el-form-item :label="$t('tool.openClient.appId')">
          <el-input
            v-model="form.appId"
            disabled
          />
        </el-form-item>
        <el-form-item :label="$t('tool.openClient.appSecret')">
          <el-input
            v-model="form.appSecret"
            disabled
          />
        </el-form-item>
        <el-form-item :label="$t('tool.openClient.status')">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button
            :loading="dialog.loading"
            type="primary"
            @click="submitForm"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { addOpenClient, deleteOpenClient, getOpenClientList, type OpenClientInfo, updateOpenClient } from "@/api/tool/openClient";
import { i18n } from "@/i18n";

// Utility function to generate random string
const generateRandomString = (length: number) => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

// Data
const loading = ref(false);
const total = ref(0);
const list = ref<OpenClientInfo[]>([]);
const queryParams = ref({
  current: 1,
  size: 10,
  appName: "",
  appId: ""
});

// Dialog control
const dialog = ref({
  visible: false,
  title: "",
  loading: false
});

// Form
const form = ref<OpenClientInfo>({
  appName: "",
  appId: "",
  appSecret: "",
  status: 1
});
const formRef = ref<FormInstance>();
const rules = {
  appName: [{ required: true, message: i18n.global.t("tool.openClient.appName"), trigger: "blur" }]
};

// Secret control
const secretVisibility = ref(new Map<string, boolean>());

const toggleSecret = (appId: string) => {
  secretVisibility.value.set(appId, !secretVisibility.value.get(appId));
};

// Methods
const handleQuery = async () => {
  loading.value = true;
  try {
    const { data } = await getOpenClientList(queryParams.value);
    list.value = data.records;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

const resetQuery = () => {
  queryParams.value = {
    current: 1,
    size: 10,
    appName: "",
    appId: ""
  };
  handleQuery();
};

const handleAdd = () => {
  dialog.value.visible = true;
  dialog.value.title = i18n.global.t("tool.openClient.add");
  form.value = {
    appName: "",
    appId: generateRandomString(16), // Generate 16-character random ID
    appSecret: generateRandomString(32), // Generate 32-character random secret
    status: 1
  };
};

const handleUpdate = (row: OpenClientInfo) => {
  dialog.value.visible = true;
  dialog.value.title = i18n.global.t("tool.openClient.edit");
  form.value = { ...row };
};

const handleDelete = async (ids: number[]) => {
  await ElMessageBox.confirm(i18n.global.t("tool.openClient.confirmDelete"), i18n.global.t("common.tip"), {
    type: "warning"
  });

  try {
    await deleteOpenClient(ids);
    ElMessage.success(i18n.global.t("common.deleteSuccess"));
    handleQuery();
  } catch (error) {
    console.error(error);
  }
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();

  dialog.value.loading = true;
  try {
    if (form.value.id) {
      await updateOpenClient(form.value);
    } else {
      await addOpenClient(form.value);
    }
    dialog.value.visible = false;
    ElMessage.success(i18n.global.t("common.saveSuccess"));
    handleQuery();
  } finally {
    dialog.value.loading = false;
  }
};

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 1rem;
}

.secret-display {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
